import json

from flask import Blueprint, request, jsonify

from service.model import ai_understand_image, query_story, call_ai_images, call_ai_lan

guide_bp = Blueprint('guide', __name__)


@guide_bp.route('/api/image', methods=['GET'])
def understand_image():
    """
    识别图片
    """
    image = request.form['image']
    if image is not None:
        return jsonify({"code": 500, "message": '参数错误'})
    # 调用ai识别图片
    content = ai_understand_image(image)
    # 查询内容的相关故事
    story = query_story(content)
    return jsonify({
        "code": 200,
        "message": "",
        "data": {
            "image_response": content,
            "story_response": story,
        }
    })


global_content = ""


@guide_bp.route('/api/batch_img', methods=['POST'])
def batch_understand_image():
    """
    批量识别图片
    """
    images = request.form['images']
    if images == "":
        return jsonify({"code": 500, "message": '参数错误'})
    images_arr = json.loads(images)
    print("请求数据长度", len(images_arr))
    result = call_ai_images(images_arr)
    print(result)
    if result.status_code == 200:
        try:
            content = result.output.choices[0].message.content[0]['text']
        except (KeyError, IndexError) as e:
            print(f"错误：{e}")
            content = None  # 设置默认值
        print(content)
        if content is None:
            return jsonify({
                "code": 500,
                "msg": "",
                "data": "场景没看清，请重试一次吧"
            })
        res = query_story(content)
        global global_content
        global_content += res
        return jsonify({
            "code": 200,
            "msg": "",
            "data": res,
        })
    else:
        return jsonify({
            "code": 500,
            "msg": "",
            "data": "失败"
        })


@guide_bp.route('/api/summarize', methods=['GET'])
def summarize():
    print(global_content)
    role = "你擅长内容总结，将我提供的内容进行分点总结。需要控制在200字以内，用发朋友圈的文案类型。"
    result = call_ai_lan(role, global_content)
    return jsonify({
        "code": 200,
        "msg": "",
        "data": result
    })
